package com.acce.product.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.acce.system.dao.ICompanyRelationshipDao;
import com.acce.base.pojo.ArgsPojo;
import com.acce.system.pojo.CompanyRelationship;
import com.acce.base.pojo.ReturnPojo;
import com.acce.product.config.ErrorCodes;
import com.acce.product.config.HeaderType;
import com.acce.product.dao.IBuyGoodsDao;
import com.acce.product.dao.IInquiryListDao;
import com.acce.product.dao.IPurchaseListDao;
import com.acce.product.exception.ApplicationException;
import com.acce.product.jpush.PushMessage;
import com.acce.product.pojo.BuyGoods;
import com.acce.product.pojo.InquiryHeader;
import com.acce.product.pojo.InquiryList;
import com.acce.product.pojo.PurchaseHeader;
import com.acce.product.pojo.PurchaseList;
import com.acce.product.service.InquiryListService;
import com.acce.product.utils.PushMsgUtil;
import com.acce.product.utils.Utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Service("inquiryListService")
public class InquiryListServiceImpl implements InquiryListService {

	private Logger logger = Logger.getLogger(InquiryListServiceImpl.class);
	
	@Resource
	IInquiryListDao inquiryListDao;
	
	@Resource
	IPurchaseListDao purchaseListDao;
	
	@Resource
	IBuyGoodsDao buyGoodsDao;
	
	@Resource
	ICompanyRelationshipDao companyRelationshipDao;
	
	public ReturnPojo findInquiryList(ArgsPojo args) {
		String business = args.getBusiness();
		JSONObject jb = (JSONObject)JSONObject.parse(business);
//		String atUserId = jb.getString("atUserId");
		String frontId = jb.getString("frontId");
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		InquiryList inquiryList = new InquiryList();
		inquiryList.setFrontId(frontId);
		inquiryList.setValidity("1");
		
		logger.info("nsy-product:findInquiryHeader find inquiryLists");
		
		List<InquiryList> inquiryLists = inquiryListDao.getInquiryListByCondition(inquiryList);
		
		logger.info("nsy-product:findInquiryHeader find inquiryLists: " + ((inquiryLists==null)?"null":inquiryLists.size()));
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		result.setResult(inquiryLists);
		return result;
	}
	
	public ReturnPojo findInquiryHeader(ArgsPojo args) {
		String business = args.getBusiness();
		JSONObject jb = (JSONObject)JSONObject.parse(business);
//		String atUserId = jb.getString("atUserId");
		String sendCompanyId = jb.getString("sendCompanyId");
		String createTime = jb.getString("createTime");
		String direction = jb.getString("direction");
		String count = jb.getString("count");
		if(StringUtils.isEmpty(direction)) {
			direction = "0";
		}
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		InquiryHeader inquiryHeader = new InquiryHeader();
		inquiryHeader.setSendCompanyId(sendCompanyId);
		inquiryHeader.setValidity("1");
		logger.info("sendCompanyId:" + sendCompanyId);
		//采购商只查询未报价的询价单
		inquiryHeader.setInquiryState("0");
		if(!StringUtils.isEmpty(createTime)) {
			logger.info("nsy-product:findInquiryHeader find inquiryHeaders scroll up/down.");
			inquiryHeader.setCreateTime(createTime);
		} else {
			logger.info("nsy-product:findInquiryHeader find inquiryHeaders first time quiry.");
		}
		inquiryHeader.setDirection(Integer.valueOf(direction));
		inquiryHeader.setCount(Integer.valueOf(count));
		
		logger.info("nsy-product:findInquiryHeader find inquiryHeaders");
		
		List<InquiryHeader> inquiryHeaders = inquiryListDao.getInquiryHeaderByCondition(inquiryHeader);
		
		logger.info("nsy-product:findInquiryHeader find inquiryHeaders: " + ((inquiryHeaders==null)?"null":inquiryHeaders.size()));
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		result.setResult(inquiryHeaders);
		return result;
	}
	
	public ReturnPojo findChaInqHeader(ArgsPojo args) {
		String business = args.getBusiness();
		JSONObject jb = (JSONObject)JSONObject.parse(business);
//		String atUserId = jb.getString("atUserId");
		String recCompanyId = jb.getString("recCompanyId");
		String createTime = jb.getString("createTime");
		String direction = jb.getString("direction");
		String count = jb.getString("count");
		if(StringUtils.isEmpty(direction)) {
			direction = "0";
		}
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		InquiryHeader inquiryHeader = new InquiryHeader();
		inquiryHeader.setRecCompanyId(recCompanyId);
		inquiryHeader.setValidity("1");
		logger.info("recCompanyId:" + recCompanyId);
		if(!StringUtils.isEmpty(createTime)) {
			logger.info("nsy-product:findChaInqHeader find inquiryHeaders scroll up/down.");
			inquiryHeader.setCreateTime(createTime);
		} else {
			logger.info("nsy-product:findChaInqHeader find inquiryHeaders first time quiry.");
		}
		inquiryHeader.setDirection(Integer.valueOf(direction));
		inquiryHeader.setCount(Integer.valueOf(count));
		//查询未报价的询价单
		inquiryHeader.setInquiryState("0");
		
		logger.info("nsy-product:findChaInqHeader find inquiryHeaders");
		
		List<InquiryHeader> inquiryHeaders = inquiryListDao.getInquiryHeaderByCondition(inquiryHeader);
		
		logger.info("nsy-product:findChaInqHeader find inquiryHeaders: " + ((inquiryHeaders==null)?"null":inquiryHeaders.size()));
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		result.setResult(inquiryHeaders);
		return result;
	}

	@Transactional
	public ReturnPojo insertInquiryList(ArgsPojo args) throws ApplicationException {
		String business = args.getBusiness();
		logger.info("nsy-product::insertInquiryList business: \n" + business);
		JSONObject jb = (JSONObject)JSONObject.parse(business);
		String atUserId = jb.getString("atUserId");
		JSONArray inquiryChannels = (JSONArray)jb.getJSONArray("channels");
		JSONObject purchaseHeader = (JSONObject)jb.getJSONObject("purchaseHeader");

		String currTime = Utils.getCurrTimeMillions();
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());

		PurchaseHeader purHeader = JSONObject.parseObject(purchaseHeader.toJSONString(), PurchaseHeader.class);
		InquiryHeader inqHeader = JSONObject.parseObject(purchaseHeader.toJSONString(), InquiryHeader.class);

		PurchaseHeader pHeader = new PurchaseHeader();
		pHeader.setFrontId(purHeader.getFrontId());
		PurchaseHeader ppHeader = purchaseListDao.getPurchaseHeaderById(pHeader);
		
		PurchaseList purcList = new PurchaseList();
		purcList.setFrontId(purHeader.getFrontId());
		List<PurchaseList> purchaseList = purchaseListDao.getPurchaseListByCondition(purcList);
		JSONArray inquiryList = (JSONArray)JSONArray.toJSON(purchaseList);

		//有几个供应商就复制几分数据, 原则不应该在循环中做数据库操作, 由于供应商个数不会太多, 故暂时这样选择
		List<CompanyRelationship> companyRelationships = new ArrayList<CompanyRelationship>();
		for(int k=0; k<inquiryChannels.size(); k++) {
			JSONObject cJson = (JSONObject)inquiryChannels.get(k);
			CompanyRelationship channel = JSONObject.parseObject(cJson.toJSONString(), CompanyRelationship.class);
			String frontId = atUserId + System.currentTimeMillis();
			inqHeader.setHeaderType(HeaderType.inquiry.getType());
			inqHeader.setPurchaseId(ppHeader.getPurchaseId());
			inqHeader.setInquiryState("0");
			inqHeader.setValidity("1");
			inqHeader.setFrontId(frontId);
			inqHeader.setSendTime(currTime);
			inqHeader.setCreateTime(currTime);
			inqHeader.setSyncType("1");
			inqHeader.setSyncTime(currTime);
			
			inqHeader.setRecCompanyId(channel.getChannelCompanyId());
			inqHeader.setRecCompanyName(channel.getChannelCompanyName());
			inqHeader.setRecUserId(channel.getContactUserId());
			inqHeader.setRecUserName(channel.getContactName());
			
			List<InquiryList> list = new ArrayList<InquiryList>();
			for(int i=0; i<inquiryList.size(); i++) {
				JSONObject purList = (JSONObject)inquiryList.get(i);
				InquiryList pList = JSONObject.parseObject(purList.toJSONString(), InquiryList.class);
				pList.setInquiryListId(Utils.makeInquiryListId());
				pList.setInquiryQuantity(pList.getPurchaseQuantity());
				pList.setValidity("1");
				pList.setFrontId(frontId);
				pList.setSyncType("1");
				pList.setSyncTime(currTime);
				list.add(pList);
			}
			
			int inquiryNum = 0;
			try {
				Integer.valueOf(channel.getInquiryNum());
			} catch(Exception ex) {
				inquiryNum = 0;
			}
			channel.setInquiryNum(String.valueOf(++inquiryNum));
			companyRelationships.add(channel);
			
			inquiryListDao.insertInquiryHeader(inqHeader);
			inquiryListDao.insertBatchInquiryList(list);
			
			PushMessage pm = new PushMessage(inqHeader);
			PushMsgUtil.pushAndroidNotificationMessage(pm);
		}
		logger.info("nsy-product:insertInquiryList insert inquiry list.");
		
		purHeader.setPurchaseState("1");
		purchaseListDao.updatePurchaseHeader(purHeader);
		logger.info("nsy-product:insertInquiryList update purchase header status to inquiry.");

		companyRelationshipDao.updateBatchCompanyRelationshipByProduct(companyRelationships);
		logger.info("nsy-product:insertInquiryList companyRelationships inquiry num++.");
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		return result;
	}

	@Transactional
	public ReturnPojo insertDirInqList(ArgsPojo args) throws ApplicationException {
		String business = args.getBusiness();
		logger.info("nsy-product::insertDirInqList business: \n" + business);
		JSONObject jb = (JSONObject)JSONObject.parse(business);
		String atUserId = jb.getString("atUserId");
		JSONArray inquiryChannels = (JSONArray)jb.getJSONArray("channels");
		JSONObject purchaseHeader = (JSONObject)jb.getJSONObject("purchaseHeader");
		JSONArray purchaseList = (JSONArray)jb.getJSONArray("purchaseList");

		String currTime = Utils.getCurrTimeMillions();
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		PurchaseHeader purHeader = JSONObject.parseObject(purchaseHeader.toJSONString(), PurchaseHeader.class);
		
		String frontId = atUserId + System.currentTimeMillis();
		purHeader.setPurchaseId(Utils.makePurchaseId());
		purHeader.setValidity("1");
		purHeader.setFrontId(frontId);
		purHeader.setPurchaseState("1");
		purHeader.setCreateTime(currTime);
		purHeader.setSyncType("1");
		purHeader.setSyncTime(currTime);
		purchaseListDao.insertPurchaseHeader(purHeader);
		logger.info("nsy-product:insertInquiryList insert purchase header.");
		
		List<PurchaseList> list = new ArrayList<PurchaseList>();
		List<BuyGoods> goodsList = new ArrayList<BuyGoods>();
		for(int i=0; i<purchaseList.size(); i++) {
			JSONObject purList = (JSONObject)purchaseList.get(i);
			PurchaseList pList = JSONObject.parseObject(purList.toJSONString(), PurchaseList.class);
			pList.setValidity("1");
			pList.setFrontId(frontId);
			pList.setPurchaseListId(Utils.makePurchaseListId());
			list.add(pList);
			
			BuyGoods goods = new BuyGoods();
			goods.setGoodsKingdom(pList.getGoodsKingdom());
			goods.setSon(pList.getGoodsFamily());
			goods.setLevelNum("3");
			goods.setCompanyId(purHeader.getSendCompanyId());
			goods.setCompanyDefaultState("1");
			goods.setValidity("1");
			goods.setSyncType("1");
			goods.setSyncTime(currTime);
			goods.setProQuantity(pList.getPurchaseQuantity());
			logger.info("nsy-product::prepare to updateBatchBuyGoods: goodsKingdom-"+goods.getGoodsKingdom()
				+ ", son-" + goods.getSon() + ", companyId-" + goods.getCompanyId());
			goodsList.add(goods);
		}
		purchaseListDao.insertBatchPurchaseList(list);
		logger.info("nsy-product:insertInquiryList insert purchase list.");
		
		InquiryHeader inqHeader = JSONObject.parseObject(purchaseHeader.toJSONString(), InquiryHeader.class);
		
		//有几个供应商就复制几分数据, 原则不应该在循环中做数据库操作, 由于供应商个数不会太多, 故暂时这样选择
		List<CompanyRelationship> companyRelationships = new ArrayList<CompanyRelationship>();
		for(int k=0; k<inquiryChannels.size(); k++) {
			JSONObject cJson = (JSONObject)inquiryChannels.get(k);
			CompanyRelationship channel = JSONObject.parseObject(cJson.toJSONString(), CompanyRelationship.class);
			String infrontId = atUserId + System.currentTimeMillis();
			inqHeader.setHeaderType(HeaderType.inquiry.getType());
			inqHeader.setPurchaseId(purHeader.getPurchaseId());
			inqHeader.setInquiryState("0");
			inqHeader.setValidity("1");
			inqHeader.setFrontId(infrontId);
			inqHeader.setSendTime(currTime);
			inqHeader.setCreateTime(currTime);
			inqHeader.setSyncType("1");
			inqHeader.setSyncTime(currTime);
			
			inqHeader.setRecCompanyId(channel.getChannelCompanyId());
			inqHeader.setRecCompanyName(channel.getChannelCompanyName());
			inqHeader.setRecUserId(channel.getContactUserId());
			inqHeader.setRecUserName(channel.getContactName());
			
			List<InquiryList> ilist = new ArrayList<InquiryList>();
			for(int i=0; i<purchaseList.size(); i++) {
				JSONObject purList = (JSONObject)purchaseList.get(i);
				InquiryList pList = JSONObject.parseObject(purList.toJSONString(), InquiryList.class);
				pList.setInquiryListId(Utils.makeInquiryListId());
				pList.setInquiryQuantity(pList.getPurchaseQuantity());
				pList.setValidity("1");
				pList.setFrontId(infrontId);
				pList.setSyncType("1");
				pList.setSyncTime(currTime);
				ilist.add(pList);
			}
			
			int inquiryNum = Integer.valueOf(channel.getInquiryNum());
			channel.setInquiryNum(String.valueOf(++inquiryNum));
			companyRelationships.add(channel);
			
			inquiryListDao.insertInquiryHeader(inqHeader);
			inquiryListDao.insertBatchInquiryList(ilist);
			
			PushMessage pm = new PushMessage(inqHeader);
			PushMsgUtil.pushAndroidNotificationMessage(pm);
		}
		logger.info("nsy-product:insertInquiryList insert inquiry list.");

		companyRelationshipDao.updateBatchCompanyRelationshipByProduct(companyRelationships);
		logger.info("nsy-product:insertInquiryList companyRelationships inquiry num++.");
		
		buyGoodsDao.updateBatchBuyGoodsQuantity(goodsList);
		logger.info("nsy-product::updateBatchBuyGoods success.");
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		return result;
	}


	@Transactional
	public ReturnPojo updateInquiryList(ArgsPojo args) throws ApplicationException {
		String business = args.getBusiness();
		JSONObject jb = (JSONObject)JSONObject.parse(business);
//		String atUserId = jb.getString("atUserId");
		JSONObject inquiryHeader = (JSONObject)jb.getJSONObject("inquiryHeader");
		JSONArray inquiryList = (JSONArray)jb.getJSONArray("inquiryList");

		String currTime = Utils.getCurrTimeMillions();
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		InquiryHeader inqHeader = JSONObject.parseObject(inquiryHeader.toJSONString(), InquiryHeader.class);
		inqHeader.setSyncType("1");
		inqHeader.setSyncTime(currTime);
		List<InquiryList> list = new ArrayList<InquiryList>();
		for(int i=0; i<inquiryList.size(); i++) {
			JSONObject purList = (JSONObject)inquiryList.get(i);
			InquiryList pList = JSONObject.parseObject(purList.toJSONString(), InquiryList.class);
			list.add(pList);
		}
		inquiryListDao.updateInquiryHeader(inqHeader);
		inquiryListDao.updateBatchInquiryList(list);
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		return result;
	}

	@Transactional
	public ReturnPojo deleteInquiryList(ArgsPojo args) throws ApplicationException {
		String business = args.getBusiness();
		JSONObject jb = (JSONObject)JSONObject.parse(business);
//		String atUserId = jb.getString("atUserId");
		String frontId = jb.getString("frontId");

		String currTime = Utils.getCurrTimeMillions();
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		InquiryHeader inquiryHeader = new InquiryHeader();
		inquiryHeader.setFrontId(frontId);
		inquiryHeader.setValidity("0");
		inquiryHeader.setSyncTime(currTime);
		inquiryHeader.setSyncType("1");
		InquiryList inquiryList = new InquiryList();
		inquiryList.setFrontId(inquiryHeader.getFrontId());
		inquiryListDao.updateInquiryHeader(inquiryHeader);
		logger.info("nsy-product::deleteInquiryList ...deleted...");
		//inquiryListDao.updateInquiryList(inquiryList);
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		return result;
	}

}
